﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Model;

namespace LOPA
{
    public partial class PidPage : UserControl{

        private static List<string> _oldPidList = new List<string>();
        public PidPage()
        {
            InitializeComponent();
            dgvPid.AllowUserToAddRows = false;
         //   dgvPid.DataSource = Program.Workspace.GetPidList();
            _bindPidList.DataSource = Program.Workspace.LopaProject.PidList;
            dgvPid.DataSource = _bindPidList;
        }

        private void dgvPid_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, dgvPid.RowHeadersWidth - 4, e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), dgvPid.RowHeadersDefaultCellStyle.Font, rectangle,
                dgvPid.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }

        private void btnEdit_Click(object sender, EventArgs e){
            foreach (PID pid in Program.Workspace.LopaProject.PidList){
                _oldPidList.Add(pid.DrawingNum);
            }
            dgvPid.Enabled = true;
        }

        public void btnSave_Click(object sender, EventArgs e){
            dgvPid.Enabled = false;
            Dictionary<string ,string> diff = new Dictionary<string, string>();
            for (int i = 0; i < _oldPidList.Count; i++){
                if (!_oldPidList[i].Equals(Program.Workspace.LopaProject.PidList[i].DrawingNum)){
                    diff.Add(_oldPidList[i], Program.Workspace.LopaProject.PidList[i].DrawingNum);
                }
            }
            if (diff.Count != 0){
                Program.Workspace.OnPidListChanged(diff);
            }
            Program.Workspace.SaveProject(MainForm.mainForm.SaveFilePath);
            MessageBox.Show("图纸清单保存成功!");
        }

        public void SaveWithoutRemider(){
            dgvPid.Enabled = false;
        }

        public DataGridView DgvPid{
            get { return dgvPid; }
            set { dgvPid = value; }
        }

        private void addNewRow_Click(object sender, EventArgs e)
        {
            if (!dgvPid.Enabled) {
                return;
            }
            PID pid = new PID();
            _bindPidList.Insert(dgvPid.Rows.Count,pid);
            dgvPid.Rows[dgvPid.Rows.Count - 1].Selected = true;
            dgvPid.CurrentCell = dgvPid[1, dgvPid.Rows.Count - 1];
        }

    }
}
